package pers.w.chaptertalk;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.IReader;
import pers.w.chaptertalk.ui.books.BooksFragment;
import pers.w.chaptertalk.ui.me.MeFragment;
import pers.w.chaptertalk.ui.search.SearchFragment;

public class MainActivity extends AppCompatActivity implements IReader {
    SearchFragment searchFragment;

    public BooksFragment getBooksFragment() {
        return booksFragment;
    }

    BooksFragment booksFragment;
    MeFragment meFragment;
    HashMap<Integer, Fragment> fragments;
    FrameLayout host_Fragment;
    BottomNavigationView bottomNavigationView;
    //int[] fragmentIDs;
    int curFragmenID;
    FrameLayout loading;

   // @SuppressLint("CutPasteId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Fun.rootPath = this.getExternalFilesDir("");
        setContentView(R.layout.activity_main);
        //BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        /*AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_books, R.id.navigation_search, R.id.navigation_me)
                .build();

       NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);

        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController); */
        loading = findViewById(R.id.fl_loading);
        booksFragment = new BooksFragment();
        searchFragment = new SearchFragment();
        meFragment = new MeFragment();
        fragments = new HashMap<>();
        fragments.put(R.id.navigation_books, booksFragment);
        fragments.put(R.id.navigation_search, searchFragment);
        fragments.put(R.id.navigation_me, meFragment);

        host_Fragment = findViewById(R.id.fl_host_Fragment);

        getSupportFragmentManager().beginTransaction().replace(R.id.fl_host_Fragment, booksFragment).commitAllowingStateLoss();
        curFragmenID = R.id.navigation_books;

        bottomNavigationView = findViewById(R.id.nav_view);
        bottomNavigationView.setOnNavigationItemSelectedListener(menuItem -> {
            if (curFragmenID != menuItem.getItemId())
                switchFragment(menuItem.getItemId());
            return true;
        });

        if (PackageManager.PERMISSION_GRANTED !=
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // 判断targetSdkVersion 是否大于等于23，这个都是自己写的，一般也不用判断，直接根据自己的版本选择方法就行
            if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.M) {
                // 判断targetSdkVersion 是否大于等于23，这个都是自己写的，一般也不用判断，直接根据自己的版本选择方法就行

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                }
            }
        }
        if (PackageManager.PERMISSION_GRANTED !=
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_SETTINGS)) {
            if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.M) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_SETTINGS}, 0);
                }
            }
        }
        serviceIntent =new Intent(this,MyService.class );
        //如果直接启动前台服务就需要判断，这种后面才启用的，反而不需要，直接启动普通服务，后面再调用startForeground
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//             startForegroundService(service);
//        } else {
//            startService(service);
//        }

        startService(serviceIntent);
        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
               MainActivity.this.service = ((MyService.MyIBinder) service).getService();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        bindService(new Intent(this,MyService.class),serviceConnection, Context.BIND_AUTO_CREATE);

        load_setting();

    }

    private Intent serviceIntent;
    private MyService service;
    private ServiceConnection serviceConnection;

    public MyService getService() {
        return service;
    }

    @Override
    protected void onDestroy() {
        unbindService(serviceConnection);
        stopService(serviceIntent);
        super.onDestroy();
    }

    private boolean firstShow =true;
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (firstShow){
            firstShow=false;
            booksFragment.startBmpThread();
        }
    }

    public void showLoading(){
        loading.setVisibility(View.VISIBLE);
    }

    public void showMsg(String msg){
        final TextView tv_msg = findViewById(R.id.tv_show_msg);
        tv_msg.setText(msg);
    }

    public void hideLoading(){
        loading.setVisibility(View.INVISIBLE);
    }
    public void load_setting() {
        Properties properties = new Properties();
        try {
            InputStream is = this.openFileInput(MeFragment. CONFIG_NAME);
            properties.load(is);
            String u = properties.getProperty(USER, "");//用户名
            if (u.length() >= 3) {
                Fun.SHARE_MAP.put(R.string.prompt_username, u);}
            String p = properties.getProperty(PASSWORD, "");//用户名
            if (p.length() >= 6) Fun.SHARE_MAP.put(R.string.prompt_password, p);
            is.close();
        } catch (IOException e) {
            // e.printStackTrace();
        }
    }
    /**
     * 切换fragment
     */
    private void switchFragment(int showID) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //隐藏上个Fragment
        Fragment curF, showF;
        curF = fragments.get(curFragmenID);
        showF = fragments.get(showID);
        if (null != curF && null != showF) {
            transaction.hide(curF);
            if (!showF.isAdded()) {
                transaction.add(R.id.fl_host_Fragment, showF);
            }
            transaction.show(showF).commitAllowingStateLoss();

            curFragmenID = showID;
        }
    }

    private Long backPressedTime = 0L;

    @Override
    public void onBackPressed() {

        if (System.currentTimeMillis() - backPressedTime > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出阅读", Toast.LENGTH_SHORT).show();
            backPressedTime = System.currentTimeMillis();
        } else {
            finish();
            super.onBackPressed();
        }
    }
}
